#include "EditorComboBoxWidget.h"

#include "Framework/Editor.h"
#include "Theme/EditorTheme.h"

#include "Widgets/RectangleWidget.h"
#include "Widgets/TextWidget.h"
#include "Widgets/Mouse/MouseWidget.h"

#include "Widgets/Keyboard/KeyboardWidget.h"

#include "Window/EditorPopupMenuView.h"
#include "Window/EditorWindowGroupView.h"

REditorComboBoxWidget::REditorComboBoxWidget()
{
    auto Text=NewWidget<RTextWidget>(this);
    Text->Anchor.Fill(this);
    Text->Text=[this](){
        return SelectedItem.Get();
    };


    auto Mouse=NewWidget<RMouseWidget>(this);
    Mouse->Anchor.Fill(this);

    Mouse->OnClicked.BindLambda([this](const SMouseButtonEvent&){
        auto _Items=Items.Get();
        if(_Items.Empty())
        {
            return true;
        }

        SIntPoint PopupSize;
        PopupSize.X=this->PresentSize.X;
        PopupSize.Y=LineHeight*_Items.Num();

        auto DropDownParent=REditorWindowGroupView::Get()->CreatePopupMenu(
            PopupSize
            ,this
        );
        
        auto DropDown=NewWidget<RRectangleWidget>(DropDownParent);
        DropDown->Anchor.Fill(DropDownParent);

        DropDown->FillColor=REditor::Get()->CurrentTheme->BackgroundColor;
        DropDown->Radius= REditor::Get()->CurrentTheme->ImageButtonRadius;
        DropDown->BorderColor=REditor::Get()->CurrentTheme->SpliterColor;
        DropDown->BorderSize=1;
        DropDown->bClipSubWidgets=true;
        RRectangleWidgetWeakPtr DropDownWeak=DropDown;

        for(int64_t i=0;i<_Items.Num();i++)
        {
            auto Line=NewWidget<RWidget>(DropDownWeak);
            Line->Anchor.HorizontalFill(DropDownWeak);
            Line->Height=LineHeight;
            Line->Y=i*LineHeight;

            auto ItemBackground=NewWidget<RRectangleWidget>(Line);
            ItemBackground->Anchor.Fill(Line);
            ItemBackground->FillColor=REditor::Get()->CurrentTheme->HighlightColor;
            ItemBackground->Radius= REditor::Get()->CurrentTheme->ImageButtonRadius;
            
            auto ItemText=NewWidget<RTextWidget>(Line);
            ItemText->Anchor.Fill(Line);
            CString Item=_Items[i];
            ItemText->Text=[Item](){
                return Item;
            };
            ItemText->VerticalAlignment=ETextVerticalAlignment::Center;

            auto ItemMouse=NewWidget<RMouseWidget>(Line);
            ItemMouse->Anchor.Fill(Line);
            RMouseWidgetWeakPtr ItemMouseWeak=ItemMouse;
            ItemBackground->Visible=[ItemMouseWeak](){
                return ItemMouseWeak->IsHovered();
            };

            ItemMouse->OnClicked.BindLambda([this,Item](const SMouseButtonEvent&){
                //SelectedItem.Set(Item);
                OnSelectionChanged.ExecuteIfBound(Item);
                
                REditorWindowGroupView::Get()->ClosePopupMenu();
                return true;
            });
        }
        

        return true;
    });
}